package com.example.filter;

import com.alibaba.fastjson.JSON;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
@Component
public class Filter implements GatewayFilter, Ordered {
    private static final String PATH = "/login";
    private static final String CHARSET_NAME = "utf-8";
    private static final String ADMIN = "admin";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("网关gateway  filter");
        ServerHttpRequest request = exchange.getRequest();
        System.out.println(request.getPath());
        ServerHttpResponse response = exchange.getResponse();

        // 获取请求路径，
        String path = request.getPath().toString();
        // 获取请求参数中token的值
        String token = request.getQueryParams().getFirst("token");
        // 判断是否请求的login页面
        if (path.contains(PATH)) {
            return chain.filter(exchange);
            // 没有访问登录页面，判断用户是否有token
        } else if(!token.isEmpty() && ADMIN.equals(token)){
            return chain.filter(exchange);
        } else {
            // 响应结果，
            HashMap data = new HashMap();
            DataBuffer buffer = null;
            try {
                data.put("code",404);
                data.put("msg","请先登录");

                byte[] bytes = JSON.toJSONString(data).getBytes(CHARSET_NAME);
                buffer = response.bufferFactory().wrap(bytes);
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                response.getHeaders().add("Content-Type","application/json;charset=UTF-8");
            }catch (Exception e) {
                e.printStackTrace();
            }
            return response.writeWith(Mono.just(buffer));
        }

    }

    /**
     * 权重，值越小优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
